package com.yyh.json;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yyh.json.User;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

/*1.将java中的对象转换成JSON格式的字符串|JSON对象
* 2.将JSON格式的字符串|JSON对象转换成java中的对象
* */
public class Demo4 {
    public static void main(String[] args) throws Exception {
        //将User.json文件中的内容读到java程序中并转为String字符串
        BufferedReader br = new BufferedReader(new FileReader("D:\\ideaproject\\IO-code\\XML-code\\src\\com\\yyh\\json\\UserList.json"));
        //读取数据
        StringBuffer sb = new StringBuffer();
        String str = null;
        while ((str = br.readLine()) != null) {
            sb.append(str);
        }
        br.close();
        //获取到文件中json格式字符串
        String json = sb.toString();
        System.out.println(json);
        //将json格式字符串：json转为java中的对象
        List<User> list = JSON.parseArray(json, User.class);
        System.out.println(list);
        for (User user : list) {
            System.out.println(user);
        }
    }
    public static void main2(String[] args) throws Exception {
        //将User.json文件中的内容读到java程序中并转为String字符串
        BufferedReader br = new BufferedReader(new FileReader("D:\\ideaproject\\IO-code\\XML-code\\src\\com\\yyh\\json\\User.json"));
        //读取数据
        StringBuffer sb = new StringBuffer();
        String str = null;
        while ((str = br.readLine()) != null) {
            sb.append(str);
        }
        br.close();
        //获取到文件中json格式字符串
        String json = sb.toString();
        System.out.println(json);
        //将json格式字符串：json转为java中的对象
        User user = JSON.parseObject(json, User.class);
        System.out.println(user);

    }
    public static void main3(String[] args) {
        //准备集合
        List<User> list = new ArrayList<User>();
        list.add(new User("张三",18,"男",new String[]{"看电影","看小说"}));
        list.add(new User("lisi",18,"男",new String[]{"打牌","看小说"}));
        list.add(new User("三三",7,"男",new String[]{"看电影","害羞"}));
        list.add(new User("力安",4,"男",new String[]{"看电影","装酷"}));
        //将集合转换成JSON格式的数组字符串
        String json = JSON.toJSONString(list);
        System.out.println(json);
        //将集合对象转换成JSON对象
        JSONArray jsonArray = (JSONArray) JSON.toJSON(list);
        System.out.println(jsonArray);
    }
    public static void main1(String[] args) {
        //创建user对象
        User user = new User("张三", 18, "男", new String[]{"看电影","看小说"});
        //将user对象转换成JSON格式的字符串
        String json = JSON.toJSONString(user);
        //将user对象转换成JSON对象
        JSONObject jsonObject = (JSONObject) JSON.toJSON(user);
        System.out.println(jsonObject);

    }
}
